import { CaretRight, Tag as TagIcon, Plus } from '@phosphor-icons/react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import clsx from 'clsx';
import { useNormalizedQuery, useLibraryMutation } from '../../context';
import type { Tag } from '@sd/ts-client';

interface TagsGroupProps {
	isCollapsed: boolean;
	onToggle: () => void;
}

interface TagItemProps {
	tag: Tag;
	depth?: number;
}

function TagItem({ tag, depth = 0 }: TagItemProps) {
	const navigate = useNavigate();
	const [isExpanded, setIsExpanded] = useState(false);

	// TODO: Fetch children when hierarchy is implemented
	const children: Tag[] = [];
	const hasChildren = children.length > 0;

	const handleClick = () => {
		navigate(`/tag/${tag.id}`);
	};

	return (
		<div>
			<button
				onClick={handleClick}
				className={clsx(
					'flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-sm font-medium text-sidebar-ink-dull hover:bg-sidebar-box hover:text-sidebar-ink transition-colors',
					tag.privacy_level === 'Archive' && 'opacity-50',
					tag.privacy_level === 'Hidden' && 'opacity-25'
				)}
				style={{ paddingLeft: `${8 + depth * 12}px` }}
			>
				{/* Expand/Collapse for children */}
				{hasChildren && (
					<CaretRight
						size={10}
						weight="bold"
						className={clsx(
							'transition-transform flex-shrink-0',
							isExpanded && 'rotate-90'
						)}
						onClick={(e) => {
							e.stopPropagation();
							setIsExpanded(!isExpanded);
						}}
					/>
				)}

				{/* Color dot or icon */}
				{tag.icon ? (
					<TagIcon size={16} weight="bold" style={{ color: tag.color || '#3B82F6' }} />
				) : (
					<span
						className="size-2 rounded-full flex-shrink-0"
						style={{ backgroundColor: tag.color || '#3B82F6' }}
					/>
				)}

				{/* Tag name */}
				<span className="flex-1 truncate text-left">{tag.canonical_name}</span>

				{/* File count badge (if available) */}
				{/* TODO: Add file count when available from backend */}
			</button>

			{/* Children (recursive) */}
			{isExpanded &&
				children.map((child) => <TagItem key={child.id} tag={child} depth={depth + 1} />)}
		</div>
	);
}

export function TagsGroup({ isCollapsed, onToggle }: TagsGroupProps) {
	const navigate = useNavigate();
	const [isCreating, setIsCreating] = useState(false);
	const [newTagName, setNewTagName] = useState('');

	const createTag = useLibraryMutation('tags.create');

	// Fetch tags with real-time updates using search with empty query
	const { data: tagsData, isLoading } = useNormalizedQuery({
		wireMethod: 'query:tags.search',
		input: { query: '' },
		resourceType: 'tag'
	});

	// Extract tags from search results (tags is an array of { tag, relevance, ... })
	const tags = tagsData?.tags?.map((result: any) => result.tag) ?? [];

	const handleCreateTag = async () => {
		if (!newTagName.trim()) return;

		try {
			const result = await createTag.mutateAsync({
				canonical_name: newTagName.trim(),
				aliases: [],
				color: `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`,
			});

			// Navigate to the new tag
			if (result?.tag?.id) {
				navigate(`/tag/${result.tag.id}`);
			}

			setNewTagName('');
			setIsCreating(false);
		} catch (err) {
			console.error('Failed to create tag:', err);
		}
	};

	return (
		<div>
			{/* Header */}
			<button
				onClick={onToggle}
				className="mb-1 flex w-full items-center gap-2 px-1 text-xs font-semibold uppercase tracking-wider text-sidebar-ink-faint hover:text-sidebar-ink"
			>
				<CaretRight
					className={clsx('transition-transform', !isCollapsed && 'rotate-90')}
					size={10}
					weight="bold"
				/>
				<span>Tags</span>
				{tags.length > 0 && (
					<span className="ml-auto text-sidebar-ink-faint">{tags.length}</span>
				)}
			</button>

			{/* Items */}
			{!isCollapsed && (
				<div className="space-y-0.5">
					{isLoading ? (
						<div className="px-2 py-1 text-xs text-sidebar-ink-faint">Loading...</div>
					) : tags.length === 0 ? (
						<div className="px-2 py-1 text-xs text-sidebar-ink-faint">No tags yet</div>
					) : (
						tags.map((tag) => <TagItem key={tag.id} tag={tag} />)
					)}

					{/* Create Tag Button/Input */}
					{isCreating ? (
						<div className="px-2 py-1.5">
							<input
								type="text"
								value={newTagName}
								onChange={(e) => setNewTagName(e.target.value)}
								onKeyDown={(e) => {
									if (e.key === 'Enter') {
										handleCreateTag();
									} else if (e.key === 'Escape') {
										setIsCreating(false);
										setNewTagName('');
									}
								}}
								onBlur={() => {
									if (!newTagName.trim()) {
										setIsCreating(false);
									}
								}}
								placeholder="Tag name..."
								autoFocus
								className="w-full px-2 py-1 text-xs rounded-md bg-sidebar-box border border-sidebar-line text-sidebar-ink placeholder:text-sidebar-ink-faint outline-none focus:border-accent"
							/>
						</div>
					) : (
						<button
							onClick={() => setIsCreating(true)}
							className="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs font-medium text-sidebar-ink-dull hover:bg-sidebar-box hover:text-sidebar-ink transition-colors"
						>
							<Plus size={12} weight="bold" />
							<span>New Tag</span>
						</button>
					)}
				</div>
			)}
		</div>
	);
}
